import json

from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.views import View

from django_redis import get_redis_connection
from utils.response_code import RETCODE, err_msg
from django.contrib.auth import login, logout,authenticate
from django import http
from apps.users.form import RegisterForm, LoginForm, ResetPwdForm, UserInfoForm
from apps.users.models import User, UserInfo




# Create your views here.
# uid=cf61cbf9-9ab2-400c-b880-951aefe4e6c9
class RegisterView(View):

    def get(self, request):
        '''
        提供注册页面
       :param request:
       :return: 注册页面
       '''
        return render(request, 'register.html')


    def post(self, request):
        '''
        提供注册逻辑
        :param request:
        :return: 主页
        '''
        register_form = RegisterForm(request.POST)
        #表单校验
        #如果成功
        if register_form.is_valid():
            #获取表单验证的数据
            username=register_form.cleaned_data.get('username')
            password=register_form.cleaned_data.get('password')
            email=register_form.cleaned_data.get('email')
            
            # 检查用户名是否已存在
            if User.objects.filter(username=username).exists():
                return render(request, 'register.html', {'register_errmsg': '用户名已经被注册'})
                
            #验证邮箱验证码
            email_code_client=request.POST.get('email_code')
            redis_conn=get_redis_connection('verify_code')
            #获取服务端验证码
            email_code_server=redis_conn.get('email_%s'%email)
            #防止验证码重复使用
            redis_conn.delete('email_%s'%email)
            #判断验证码是否失效
            if email_code_server is None:
                #返回注册页面
                return render(request,'register.html',{'register_errmsg': '验证码已失效'})
            email_code_server=email_code_server.decode()
            #验证验证码是否错误
            if email_code_client!=email_code_server:
                return render(request,'register.html',{'register_errmsg':'输入邮箱验证码有误'})
            #保存到数据库
            try:
                user=User.objects.create_user(username=username,password=password,email=email)
            except Exception as e:
                print(e)
                return render(request,'register.html',{'register_errmsg':'注册失败'})
            #状态保持
            login(request,user)
            responce=redirect('contents:index')
            responce.set_cookie('username',user.username,60*60*24*3)
            return responce
        #表单校验失败
        else:
            return render(request,'register.html',{'register_errmsg':list(register_form.errors.values())[0][0]})

class UsernameCountView(View):
    '''判断用户名是否重复'''
    def get(self,request,username):
        '''
        :param request:
        :param username: 用户名
        :return: 用户名是否重复 JSON
        '''
        count=User.objects.filter(username=username).count()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','count':count})

class LoginView(View):
    def get(self,request):
        '''
        提供用户登录页面
        :param request:
        :return: 登录页面
        '''
        return render(request,'login.html')

    def post(self,request):
        '''
        提供用户登录逻辑
        :param request:
        :return: 主页
        '''
        #测试
        # request.POST=request.GET

        login_form=LoginForm(request.POST)
        #连接redis "image_%s"%uuid
        # redis_conn=get_redis_connection('verify_code')

        if login_form.is_valid():
            username=login_form.cleaned_data.get('username')
            password=login_form.cleaned_data.get('password')
            print(username,password)
            remembered = login_form.cleaned_data.get('remembered')
            print(type(remembered),remembered)
            if not all([username,password]):
                return http.HttpResponseForbidden('缺少必传参数')
            user=authenticate(username=username,password=password)
            if user is None:
                return render(request,'login.html',{'errmsg_login':'账号或者密码错误'})

            login(request,user)
            if remembered:
                request.session.set_expiry(None)
            else:
                request.session.set_expiry(0)

            #是否重定向到需要登录权限的网站
            next=request.GET.get('next')
            if next:
                response=redirect(next)
            else:
                response=redirect('contents:index')
            print('登录成功')
            return response

        return render(request,'login.html',{'errmsg_login':list(login_form.errors.values())[0][0]})
class LogoutView(View):
    def get(self,request):
        '''
        退出登录逻辑
        :param request:
        :return: 首页
        '''
        #重定向到首页
        logout(request)
        responce=redirect('contents:index')
        responce.delete_cookie('username')
        return responce

class ResetPasswordView(View):
    def get(self,request):
        '''
        提供重设密码网页
        :param request:
        :return: 'reset_password.html'页面
        '''
        return render(request,'reset_password.html')
    def post(self,request):
        '''
        重新设置密码
        :param request:
        :return:
        '''
        reset_pwd_form=ResetPwdForm(request.POST)
        if reset_pwd_form.is_valid():

            email_code_client=reset_pwd_form.cleaned_data.get('email_code')
            email = reset_pwd_form.cleaned_data.get('email')
            print(email)
            redis_conn=get_redis_connection('verify_code')
            email_code_server=redis_conn.get('email_%s'%email)
            redis_conn.delete('email_%s'%email)

            if email_code_server is None:
                return render(request,'reset_password.html',{'errmsg_email':'邮箱验证码失效'})
            if email_code_server.decode()!=email_code_client:

                return render(request,'reset_password.html',{'errmsg_email':'邮箱验证码有误'})

            password = reset_pwd_form.cleaned_data.get('password')
            try:
                user=User.objects.get(email=email)
                user.set_password(password)
                user.save()
                return redirect('users:login')
            except Exception as e:
                print(e)
                return render(request,'reset_password.html',{'errmsg_email':'该邮箱未注册'})
        return render(request,'reset_password.html',{'errmsg_email':'输入有误'})

class UserInfoView(LoginRequiredMixin,View):
    login_url = '/users/login/'
    def get(self,request):
        '''
        用户个人中心
        :param request:
        :return: 用户个人中心页面
        '''
        user=request.user
        try:
            userinfo=UserInfo.objects.get(user=user)
        except Exception as e:
            print(e)
            userinfo=UserInfo.objects.create(user=user)
        context=userinfo.__dict__
        context.pop('_state')
        context.pop('id')
        # return http.JsonResponse(context)
        return render(request,'userinfo.html',context=context)
    def post(self,request):
        '''
        修改用户个人信息
        :param request:
        :return:
        '''
        form = UserInfoForm(request.POST)
        user = request.user
        if form.is_valid():
            formdict = form.cleaned_data
            formdict['user'] = user
            formdict.pop('email')
            try:
                UserInfo.objects.filter(user=user).update(**formdict)
            except UserInfo.DoesNotExist:
                UserInfo.objects.create(user=user)
                UserInfo.objects.filter(user=user).update(**formdict)
            except Exception as e:
                print(e)
                return redirect('users:userinfo')
        else:
            print(form.errors)
            return render(request,'userinfo.html')
        return redirect('users:userinfo')


# 在文件末尾添加
class PerfectInfoView(LoginRequiredMixin, View):
    """完善用户信息视图"""
    login_url = '/users/login/'
    
    def get(self, request):
        """展示问卷页面"""
        # 获取用户问卷信息
        user = request.user
        try:
            survey = user.survey
        except:
            survey = None
            
        return render(request, 'perfect_info.html', {'survey': survey})
        
    def post(self, request):
        """处理问卷提交"""
        user = request.user
        # 获取表单数据
        place = request.POST.get('place')
        age_group = request.POST.get('age_group')
        want_city = request.POST.get('want_city')
        want_job = request.POST.get('want_job')
        work_experience = request.POST.get('work_experience', 0)
        real_name = request.POST.get('real_name')
        phone = request.POST.get('phone')
        
        # 更新或创建问卷信息
        try:
            survey = user.survey
            # 更新现有记录
            survey.place = place
            survey.age_group = age_group
            survey.want_city = want_city
            survey.want_job = want_job
            survey.work_experience = work_experience
            survey.real_name = real_name
            survey.phone = phone
            survey.save()
        except:
            # 创建新记录
            from apps.users.models import UserSurvey
            UserSurvey.objects.create(
                user=user,
                place=place,
                age_group=age_group,
                want_city=want_city,
                want_job=want_job,
                work_experience=work_experience,
                real_name=real_name,
                phone=phone
            )
            
        return redirect('users:userinfo')  # 提交后重定向到用户信息页面

